<template>
  <div class="settings-page">
    <div class="container">
      <h1 class="page-title">设置</h1>
      
      <!-- 添加保存结果提示 -->
      <div v-if="saveResult.show" 
           class="save-result" 
           :class="{ 'success': saveResult.success, 'error': !saveResult.success }">
        {{ saveResult.message }}
      </div>
      
      <!-- 添加加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>加载设置中...</p>
      </div>
      
      <!-- 添加错误提示 -->
      <div v-else-if="error" class="error-container">
        <h3>获取设置失败</h3>
        <p>{{ error }}</p>
        <button class="btn btn-primary" @click="fetchUserData">重试</button>
      </div>
      
      <div v-else class="settings-container">
        <div class="settings-sidebar">
          <ul class="settings-menu">
            <li 
              class="menu-item"
              v-for="(section, index) in settingsSections"
              :key="index"
              :class="{ 'active': activeSection === section.id }"
              @click="activeSection = section.id"
            >
              {{ section.title }}
            </li>
          </ul>
        </div>
        
        <div class="settings-content">
          <!-- 账号设置 -->
          <div v-if="activeSection === 'account'" class="settings-section">
            <div class="section-header">
              <h2 class="section-title">账号设置</h2>
              <button class="btn-refresh" @click="refreshUserData" title="刷新资料">
                <i class="refresh-icon">↻</i> 刷新
              </button>
            </div>
            
            <form @submit.prevent="saveAccountSettings" class="settings-form">
              <!-- 添加头像上传功能 -->
              <div class="form-group avatar-upload-group">
                <label>头像</label>
                <div class="avatar-container">
                  <div class="current-avatar" @click="triggerAvatarUpload">
                    <img v-if="accountSettings.avatar" :src="accountSettings.avatar" alt="当前头像" class="avatar-preview" />
                    <div v-else class="default-avatar" :style="{ background: generateGradient() }">
                      {{ userInitial }}
                    </div>
                    <div class="avatar-overlay">
                      <span class="avatar-edit-icon">📷</span>
                    </div>
                    <!-- 添加上传进度显示 -->
                    <div v-if="uploadProgress > 0 && uploadProgress < 100" class="avatar-progress">
                      <div class="progress-bar" :style="{ width: uploadProgress + '%' }"></div>
                      <div class="progress-text">{{ uploadProgress }}%</div>
                    </div>
                  </div>
                  <div class="avatar-actions">
                    <button type="button" class="btn btn-outline btn-sm" @click="triggerAvatarUpload">
                      {{ accountSettings.avatar ? '更换头像' : '上传头像' }}
                    </button>
                    <button 
                      v-if="accountSettings.avatar" 
                      type="button" 
                      class="btn btn-outline btn-sm btn-danger" 
                      @click="removeAvatar"
                    >
                      删除头像
                    </button>
                  </div>
                  <input 
                    type="file" 
                    id="avatar-upload" 
                    ref="avatarInput" 
                    @change="handleAvatarChange" 
                    accept="image/jpeg,image/png,image/gif" 
                    style="display: none;"
                  />
                </div>
              </div>
              
              <div class="form-group">
                <label for="userName">用户名</label>
                <input 
                  type="text" 
                  id="userName" 
                  v-model="accountSettings.userName" 
                  class="form-control"
                  disabled
                />
                <div class="form-note">用户名不可修改</div>
              </div>
              
              <div class="form-group">
                <label for="nickName">昵称</label>
                <input 
                  type="text" 
                  id="nickName" 
                  v-model="accountSettings.nickName" 
                  class="form-control" 
                  placeholder="设置一个昵称"
                />
              </div>
              
              <div class="form-group">
                <label for="email">邮箱</label>
                <input 
                  type="email" 
                  id="email" 
                  v-model="accountSettings.email" 
                  class="form-control" 
                  placeholder="your@email.com"
                />
              </div>
              
              <div class="form-group">
                <label for="phone">手机号</label>
                <input 
                  type="tel" 
                  id="phone" 
                  v-model="accountSettings.phone" 
                  class="form-control" 
                  placeholder="输入手机号"
                />
              </div>
              
              <div class="form-group">
                <label>性别</label>
                <div class="radio-group">
                  <label class="radio-label">
                    <input type="radio" v-model="accountSettings.sex" :value="0" /> 保密
                  </label>
                  <label class="radio-label">
                    <input type="radio" v-model="accountSettings.sex" :value="1" /> 男
                  </label>
                  <label class="radio-label">
                    <input type="radio" v-model="accountSettings.sex" :value="2" /> 女
                  </label>
                </div>
              </div>
              
              <div class="form-group">
                <label for="introduce">个人简介</label>
                <textarea 
                  id="introduce" 
                  v-model="accountSettings.introduce" 
                  class="form-control form-textarea" 
                  placeholder="介绍一下自己..."
                  rows="4"
                ></textarea>
              </div>
              
              <div class="form-actions">
                <button type="submit" class="btn btn-primary" :disabled="loading">
                  <span v-if="loading">保存中...</span>
                  <span v-else>保存更改</span>
                </button>
              </div>
            </form>
          </div>
          
          <!-- 安全设置 -->
          <div v-else-if="activeSection === 'security'" class="settings-section">
            <h2 class="section-title">安全设置</h2>
            
            <form @submit.prevent="changePassword" class="settings-form">
              <div class="form-group">
                <label for="currentPassword">当前密码</label>
                <input 
                  type="password" 
                  id="currentPassword" 
                  v-model="securitySettings.currentPassword" 
                  class="form-control" 
                  placeholder="输入当前密码"
                />
              </div>
              
              <div class="form-group">
                <label for="newPassword">新密码</label>
                <input 
                  type="password" 
                  id="newPassword" 
                  v-model="securitySettings.newPassword" 
                  class="form-control" 
                  placeholder="输入新密码"
                />
                <div class="form-note">密码至少包含8个字符，包括字母、数字和特殊字符</div>
              </div>
              
              <div class="form-group">
                <label for="confirmPassword">确认新密码</label>
                <input 
                  type="password" 
                  id="confirmPassword" 
                  v-model="securitySettings.confirmPassword" 
                  class="form-control" 
                  placeholder="再次输入新密码"
                />
              </div>
              
              <div class="form-actions">
                <button type="submit" class="btn btn-primary" :disabled="isChangingPassword">
                  <span v-if="isChangingPassword">更新中...</span>
                  <span v-else>更新密码</span>
                </button>
              </div>
            </form>
          </div>
          
          <!-- 通知设置 -->
          <div v-else-if="activeSection === 'notifications'" class="settings-section">
            <h2 class="section-title">通知设置</h2>
            
            <form @submit.prevent="saveNotificationSettings" class="settings-form">
              <div class="switch-group" v-for="(setting, index) in notificationSettings" :key="index">
                <div class="switch-label">
                  <h3>{{ setting.title }}</h3>
                  <p>{{ setting.description }}</p>
                </div>
                <label class="switch">
                  <input type="checkbox" v-model="setting.enabled">
                  <span class="slider"></span>
                </label>
              </div>
              
              <div class="form-actions">
                <button type="submit" class="btn btn-primary" :disabled="isSaving">
                  <span v-if="isSaving">保存中...</span>
                  <span v-else>保存更改</span>
                </button>
              </div>
            </form>
          </div>
          
          <!-- 隐私设置 -->
          <div v-else-if="activeSection === 'privacy'" class="settings-section">
            <h2 class="section-title">隐私设置</h2>
            
            <form @submit.prevent="savePrivacySettings" class="settings-form">
              <h3 class="subsection-title">资料可见性</h3>
              
              <div class="form-group">
                <label for="profileVisibility">个人资料可见性</label>
                <select id="profileVisibility" v-model="privacySettings.profileVisibility" class="form-control">
                  <option value="public">公开 - 所有人可见</option>
                  <option value="users">用户 - 仅注册用户可见</option>
                  <option value="friends">好友 - 仅好友可见</option>
                  <option value="private">私密 - 仅自己可见</option>
                </select>
              </div>
              
              <div class="form-group">
                <label for="activityVisibility">活动记录可见性</label>
                <select id="activityVisibility" v-model="privacySettings.activityVisibility" class="form-control">
                  <option value="public">公开 - 所有人可见</option>
                  <option value="users">用户 - 仅注册用户可见</option>
                  <option value="friends">好友 - 仅好友可见</option>
                  <option value="private">私密 - 仅自己可见</option>
                </select>
              </div>
              
              <h3 class="subsection-title">数据使用</h3>
              
              <div class="checkbox-group">
                <label class="checkbox-label">
                  <input type="checkbox" v-model="privacySettings.allowDataAnalytics" />
                  <span>允许收集使用数据用于改进服务</span>
                </label>
              </div>
              
              <div class="checkbox-group">
                <label class="checkbox-label">
                  <input type="checkbox" v-model="privacySettings.allowPersonalization" />
                  <span>允许个性化推荐内容</span>
                </label>
              </div>
              
              <div class="form-actions">
                <button type="submit" class="btn btn-primary" :disabled="isSaving">
                  <span v-if="isSaving">保存中...</span>
                  <span v-else>保存更改</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getUserInfo } from '@/utils/auth'

export default {
  name: 'UserSettings',
  data() {
    return {
      activeSection: 'account',
      settingsSections: [
        { id: 'account', title: '账号设置' },
        { id: 'security', title: '安全设置' },
        { id: 'notifications', title: '通知设置' },
        { id: 'privacy', title: '隐私设置' }
      ],
      accountSettings: {
        userName: '',
        nickName: '',
        email: '',
        phone: '',
        sex: 0,
        introduce: '',
        avatar: '',
        id: null
      },
      // 添加上传进度状态
      uploadProgress: 0,
      securitySettings: {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      notificationSettings: [
        {
          title: '挑战活动通知',
          description: '接收新挑战、挑战更新和提醒的通知',
          enabled: true
        },
        {
          title: '成就通知',
          description: '当您获得新成就或荣誉时接收通知',
          enabled: true
        },
        {
          title: '系统通知',
          description: '接收系统更新、维护信息和重要公告',
          enabled: true
        },
        {
          title: '邮件通知',
          description: '通过电子邮件接收重要通知',
          enabled: false
        }
      ],
      privacySettings: {
        profileVisibility: 'public',
        activityVisibility: 'users',
        allowDataAnalytics: true,
        allowPersonalization: true
      },
      isSaving: false,
      isChangingPassword: false,
      saveResult: {
        show: false,
        success: false,
        message: ''
      },
      loading: false,
      error: null
    }
  },
  mounted() {
    // 在组件挂载后，确保URL参数被正确处理
    this.checkUrlParams();
    
    // 设置一个合理的清理时间，30秒足够完成基本操作
    setTimeout(() => {
      try {
        // 只清除与Profile数据相关的缓存，保留其他可能有用的数据
        sessionStorage.removeItem('profileData');
        sessionStorage.removeItem('profileDataTimestamp');
        
        console.log('已清除临时数据');
      } catch (e) {
        console.error('清除数据失败:', e);
      }
    }, 30000); // 30秒后清除，比60秒更合理
    
    console.log('Settings组件已挂载，当前激活的选项卡:', this.activeSection);
  },
  created() {
    console.log('Settings组件创建中...');
    
    // 首先处理URL参数，确保正确的选项卡被激活
    this.checkUrlParams();
    
    // 添加事件监听，接收Profile页面传递的数据
    this.$root.$on('profile-data-ready', this.handleProfileData);
    
    // 然后加载用户设置数据
    this.loadUserSettings();
    
    console.log('Settings组件已创建，当前激活的选项卡:', this.activeSection);
  },
  beforeDestroy() {
    // 移除事件监听，避免内存泄漏
    this.$root.$off('profile-data-ready', this.handleProfileData);
  },
  watch: {
    '$route.query': {
      handler() {
        this.checkUrlParams();
      },
      immediate: true
    }
  },
  computed: {
    // 添加用户头像初始显示的计算属性
    userInitial() {
      const name = this.accountSettings.nickName || this.accountSettings.userName || '';
      if (!name) return '用';
      
      // 如果是中文名，取第一个字
      if (/[\u4e00-\u9fa5]/.test(name)) {
        return name.charAt(0);
      }
      
      // 如果是英文名，取首字母
      return name.charAt(0).toUpperCase();
    }
  },
  methods: {
    // 添加一个辅助方法，统一获取Profile数据，减少重复代码
    getProfileDataFromSession() {
      // 不再使用sessionStorage，总是返回null触发API获取
      console.log('不使用缓存，直接从API获取最新数据');
      return null;
    },
    
    checkUrlParams() {
      const { tab } = this.$route.query;
      console.log('URL参数中的tab值:', tab);
      
      if (tab) {
        const validSections = this.settingsSections.map(section => section.id);
        if (validSections.includes(tab)) {
          this.activeSection = tab;
          console.log('已激活选项卡:', tab);
        } else {
          console.warn('无效的选项卡参数:', tab);
        }
      }
    },
    
    loadUserSettings() {
      this.loading = true;
      // 直接从API获取最新数据，不使用缓存
      this.fetchUserData();
    },
    
    // 从获取的用户数据更新表单
    setUserData(userData) {
      if (!userData) return;
      
      this.accountSettings = {
        ...this.accountSettings,
        id: userData.id || this.accountSettings.id,
        userName: userData.userName || '',
        nickName: userData.nickName || '',
        email: userData.email || '',
        phone: userData.phone || '',
        sex: userData.sex !== undefined ? userData.sex : 0,
        introduce: userData.introduce || '',
        avatar: userData.avatar || ''
      };
      
      // 更新状态
      this.loading = false;
      this.error = null;
      
      console.log('用户数据已更新到表单', this.accountSettings.userName);
    },

    // 从API获取用户数据
    fetchUserData() {
      console.log('正在从API获取最新用户数据...');
      this.loading = true;
      
      // 动态导入auth模块，避免循环依赖
      import('@/api/auth').then(module => {
        // 获取当前用户名
        const userName = this.accountSettings.userName;
        
        // 确保有用户名可用
        if (!userName) {
          // 尝试从utils/auth获取用户信息
          import('@/utils/auth').then(authUtils => {
            const userInfo = authUtils.getUserInfo();
            const userName = userInfo?.userName;
            
            if (userName) {
              // 用获取到的用户名调用API
              this.callGetCurrentUserInfo(module, userName);
            } else {
              this.loading = false;
              this.error = '获取用户数据失败: 未找到用户名';
              console.error('fetchUserData失败: 无法获取用户名');
              this.showSaveResult(false, this.error);
            }
          }).catch(error => {
            console.error('导入utils/auth模块失败:', error);
            this.loading = false;
            this.error = '系统错误: 无法加载认证工具模块';
            this.showSaveResult(false, this.error);
          });
        } else {
          // 直接使用已有的用户名调用API
          this.callGetCurrentUserInfo(module, userName);
        }
      }).catch(error => {
        console.error('导入auth模块失败:', error);
        this.loading = false;
        this.error = '系统错误: 无法加载认证模块';
        this.showSaveResult(false, this.error);
      });
    },
    
    // 辅助方法 - 调用getCurrentUserInfo
    callGetCurrentUserInfo(authModule, userName) {
      authModule.getCurrentUserInfo(userName, true) // 强制从服务器获取最新数据
        .then(response => {
          if (response && (response.code === 200 || response.success)) {
            const userData = response.data;
            
            // 更新表单数据
            this.setUserData(userData);
            
            // 显示成功提示
            this.showSaveResult(true, '已加载最新个人资料');
          } else {
            this.error = '获取用户数据失败: ' + (response?.msg || response?.message || '未知错误');
            this.showSaveResult(false, this.error);
          }
        })
        .catch(error => {
          console.error('获取用户数据失败:', error);
          this.error = '获取用户数据失败: ' + (error?.message || '未知错误');
          this.showSaveResult(false, this.error);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    updateAccountSettings(userData) {
      this.accountSettings = {
        id: userData.id,
        userName: userData.userName || '',
        nickName: userData.nickName || '',
        email: userData.email || '',
        phone: userData.phone || '',
        sex: userData.sex !== undefined ? userData.sex : 0,
        introduce: userData.introduce || userData.extJson || '',
        avatar: userData.avatar || ''
      };
    },
    
    saveAccountSettings() {
      // 先验证表单
      if (!this.accountSettings.userName) {
        this.showSaveResult(false, '用户名不能为空');
        return;
      }
      
      // 如果正在加载，不执行保存
      if (this.loading) return;
      
      console.log('开始保存账户设置...');
      this.loading = true;
      this.showSaveResult(true, '正在保存...');
      
      // 动态导入auth模块
      import('@/api/auth').then(module => {
        // 调用API保存更新
        module.updateUserInfo(this.accountSettings)
          .then(response => {
            if (response && (response.code === 200 || response.success)) {
              // 保存成功
              this.showSaveResult(true, '保存成功');
              console.log('账户设置已成功保存');
              
              // 清除缓存，确保下次获取的是最新数据
              sessionStorage.removeItem('profileData');
              sessionStorage.removeItem('profileDataTimestamp');
              
              // 发送全局事件通知其他组件数据已更新
              this.$root.$emit('user-data-updated', this.accountSettings);
              this.$root.$emit('user-info-updated'); // 兼容旧代码
              
              // 设置本地存储标记，兼容旧代码
              localStorage.setItem('userDataUpdated', 'true');
              localStorage.setItem('userDataUpdatedTime', new Date().getTime().toString());
              
              // 更新本地存储的用户信息
              import('@/utils/auth').then(authModule => {
                if (typeof authModule.setUserInfo === 'function') {
                  authModule.setUserInfo(this.accountSettings);
                  console.log('已更新本地存储的用户信息');
                }
              }).catch(e => {
                console.error('更新本地用户信息失败:', e);
              });
              
              // 重新获取最新数据
              setTimeout(() => {
                this.fetchUserData();
              }, 500);
            } else {
              // 保存失败
              const errorMsg = response?.msg || response?.message || '未知错误';
              this.showSaveResult(false, '保存失败: ' + errorMsg);
              console.error('保存账户设置失败:', errorMsg);
            }
          })
          .catch(error => {
            this.showSaveResult(false, '保存出错: ' + (error.message || '网络错误'));
            console.error('保存账户设置异常:', error);
          })
          .finally(() => {
            this.loading = false;
          });
      }).catch(error => {
        console.error('导入auth模块失败:', error);
        this.loading = false;
        this.showSaveResult(false, '系统错误: 无法加载认证模块');
      });
    },
    
    showSaveResult(success, message) {
      this.saveResult = {
        show: true,
        success,
        message
      };
      
      setTimeout(() => {
        this.saveResult.show = false;
      }, 3000);
    },

    changePassword() {
      if (!this.securitySettings.currentPassword) {
        this.showSaveResult(false, '请输入当前密码');
        return;
      }
      
      if (!this.securitySettings.newPassword) {
        this.showSaveResult(false, '请输入新密码');
        return;
      }
      
      if (this.securitySettings.newPassword.length < 8) {
        this.showSaveResult(false, '新密码必须至少包含8个字符');
        return;
      }
      
      if (this.securitySettings.newPassword !== this.securitySettings.confirmPassword) {
        this.showSaveResult(false, '两次输入的密码不一致');
        return;
      }
      
      this.isChangingPassword = true;
      
      import('@/api/auth').then(module => {
        module.updatePassword(this.securitySettings.currentPassword, this.securitySettings.newPassword)
          .then(response => {
            if (response && response.success) {
              this.showSaveResult(true, '密码已成功更新');
              this.securitySettings.currentPassword = '';
              this.securitySettings.newPassword = '';
              this.securitySettings.confirmPassword = '';
            } else {
              this.showSaveResult(false, response?.message || '更新失败，请稍后重试');
            }
          })
          .catch(error => {
            console.error('更新密码失败:', error);
            this.showSaveResult(false, error.message || '更新密码失败，请稍后重试');
          })
          .finally(() => {
            this.isChangingPassword = false;
          });
      }).catch(error => {
        console.error('加载API模块失败:', error);
        this.showSaveResult(false, '系统错误，请稍后重试');
        this.isChangingPassword = false;
      });
    },

    saveNotificationSettings() {
      this.isSaving = true;
      
      import('@/api/auth').then(module => {
        module.updateNotificationSettings(this.notificationSettings)
          .then(response => {
            if (response && response.success) {
              this.showSaveResult(true, '通知设置已成功更新');
            } else {
              this.showSaveResult(false, response?.message || '更新失败，请稍后重试');
            }
          })
          .catch(error => {
            console.error('更新通知设置失败:', error);
            this.showSaveResult(false, error.message || '更新通知设置失败，请稍后重试');
          })
          .finally(() => {
            this.isSaving = false;
          });
      }).catch(error => {
        console.error('加载API模块失败:', error);
        this.showSaveResult(false, '系统错误，请稍后重试');
        this.isSaving = false;
      });
    },

    savePrivacySettings() {
      this.isSaving = true;
      
      import('@/api/auth').then(module => {
        module.updatePrivacySettings(this.privacySettings)
          .then(response => {
            if (response && response.success) {
              this.showSaveResult(true, '隐私设置已成功更新');
            } else {
              this.showSaveResult(false, response?.message || '更新失败，请稍后重试');
            }
          })
          .catch(error => {
            console.error('更新隐私设置失败:', error);
            this.showSaveResult(false, error.message || '更新隐私设置失败，请稍后重试');
          })
          .finally(() => {
            this.isSaving = false;
          });
      }).catch(error => {
        console.error('加载API模块失败:', error);
        this.showSaveResult(false, '系统错误，请稍后重试');
        this.isSaving = false;
      });
    },

    // 刷新用户数据
    refreshUserData() {
      try {
        console.log('开始刷新用户数据...');
        this.showSaveResult(true, '正在刷新数据...');
        
        // 获取当前登录用户的基本信息，用于API调用
        const localUserInfo = getUserInfo();
        if (!localUserInfo || !localUserInfo.userName) {
          this.showSaveResult(false, '无法获取用户信息，请重新登录');
          console.error('刷新数据失败: 无法获取用户信息');
          return;
        }
        
        // 清除相关缓存
        try {
          // 仅清除与用户数据相关的缓存
          sessionStorage.removeItem('profileData');
          sessionStorage.removeItem('profileDataTimestamp');
          console.log('已清除会话存储缓存');
          
          // 清除本地存储标记
          localStorage.removeItem('userDataUpdated');
          localStorage.removeItem('userDataUpdatedTime');
          console.log('已清除本地存储标记');
        } catch (e) {
          console.error('清除缓存过程中出错:', e);
        }
        
        // 动态导入auth模块以清除API缓存
        import('@/api/auth').then(module => {
          console.log('正在尝试清除API缓存...');
          
          // 尝试调用清除缓存方法
          let cacheCleared = false;
          
          if (typeof module.clearUserInfoCache === 'function') {
            module.clearUserInfoCache();
            cacheCleared = true;
            console.log('已通过clearUserInfoCache方法清除API缓存');
          } else if (typeof module.clearCache === 'function') {
            module.clearCache();
            cacheCleared = true;
            console.log('已通过clearCache方法清除API缓存');
          }
          
          if (!cacheCleared) {
            console.warn('未找到清除缓存的方法，将直接获取最新数据');
          }
          
          // 使用用户名参数并强制刷新标志调用API
          console.log('正在获取最新用户数据，用户名:', localUserInfo.userName);
          
          // 重新获取最新数据
          module.getCurrentUserInfo(localUserInfo.userName, true)
            .then(response => {
              if (response && (response.code === 200 || response.success)) {
                const userData = response.data;
                console.log('成功获取最新用户数据');
                
                // 直接更新表单，不再缓存到sessionStorage
                this.setUserData(userData);
                this.showSaveResult(true, '已成功刷新用户数据');
              } else {
                const errorMsg = response?.msg || response?.message || '未知错误'; 
                this.error = '获取用户数据失败: ' + errorMsg;
                console.error('API返回错误:', response);
                this.showSaveResult(false, this.error);
              }
            })
            .catch(error => {
              this.error = '获取用户数据出错: ' + (error.message || '网络错误');
              console.error('API请求异常:', error);
              this.showSaveResult(false, this.error);
            })
            .finally(() => {
              this.loading = false;
            });
        }).catch(error => {
          console.error('导入auth模块失败:', error);
          this.loading = false;
          this.showSaveResult(false, '刷新数据失败: 无法加载认证模块');
        });
      } catch (e) {
        console.error('刷新数据过程中出现未预期的错误:', e);
        this.error = '系统错误: ' + (e.message || '未知错误');
        this.loading = false;
        this.showSaveResult(false, '刷新失败: ' + this.error);
      }
    },

    handleProfileData(data) {
      // 处理从Profile页面传递的数据
      console.log('从Profile页面接收到的数据:', data);
      
      if (data && data.userName) {
        // 取消任何正在进行的加载操作
        this.loading = false;
        this.error = null;
        
        // 将接收到的数据转换为accountSettings格式
        this.accountSettings = {
          id: data.id,
          userName: data.userName || '',
          nickName: data.nickName || '',
          email: data.email || '',
          phone: data.phone || '',
          sex: data.sex !== undefined ? data.sex : 0,
          introduce: data.introduce || '',
          avatar: data.avatar || ''
        };
        
        console.log('已使用Profile页面传递的数据更新Settings表单');
        
        // 显示成功提示
        this.showSaveResult(true, '已加载最新用户数据');
      }
    },

    // 触发头像上传
    triggerAvatarUpload() {
      this.$refs.avatarInput.click();
    },
    
    // 生成渐变色背景
    generateGradient() {
      const colors = [
        '#FF6B6B', '#FF8E53', '#FFD700', '#6BCB77', '#4D96FF', 
        '#9775FA', '#D37EFF', '#FF6B6B', '#48BFE3', '#56CFE1'
      ];
      
      // 基于用户名生成固定的渐变色
      const name = this.accountSettings.userName || '';
      let hash = 0;
      
      for (let i = 0; i < name.length; i++) {
        hash = name.charCodeAt(i) + ((hash << 5) - hash);
      }
      
      const index1 = Math.abs(hash) % colors.length;
      const index2 = (index1 + 3) % colors.length;
      
      return `linear-gradient(45deg, ${colors[index1]}, ${colors[index2]})`;
    },
    
    // 处理头像变更
    handleAvatarChange(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      // 检查文件类型
      const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
      if (!validTypes.includes(file.type)) {
        this.showSaveResult(false, '请选择JPG、PNG或GIF格式的图片');
        return;
      }
      
      // 检查文件大小（限制为2MB）
      const maxSize = 2 * 1024 * 1024;
      if (file.size > maxSize) {
        this.showSaveResult(false, '图片大小不能超过2MB');
        return;
      }
      
      // 创建预览URL并更新表单值
      this.showSaveResult(true, '正在处理头像...');
      
      // 重置上传进度
      this.uploadProgress = 0;
      
      // 使用FileReader读取文件内容
      const reader = new FileReader();
      reader.onload = (e) => {
        // 使用FormData封装文件，准备上传
        const formData = new FormData();
        formData.append('avatar', file);
        formData.append('userId', this.accountSettings.id);
        formData.append('userName', this.accountSettings.userName);
        
        // 调用上传API
        this.uploadAvatar(formData, e.target.result);
      };
      reader.readAsDataURL(file);
    },
    
    // 上传头像API
    uploadAvatar(formData, previewUrl) {
      // 动态导入oss模块
      import('@/api/oss').then(module => {
        // 生成包含英文大小写字母和数字的16位随机ID
        const generateRandomId = () => {
          const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
          let result = '';
          // 生成16位随机字符串
          for (let i = 0; i < 16; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
          }
          // 添加时间戳前缀，确保更高的唯一性
          return `${Date.now().toString(36)}_${result}`;
        };
        
        const randomId = generateRandomId();
        
        // 准备上传选项
        const options = {
          // 进度回调
          onProgress: (percent) => {
            this.uploadProgress = percent;
          },
          // 设置objectName格式为"用户名/avatar/随机ID"，不包含文件扩展名
          objectName: `${this.accountSettings.userName || 'anonymous'}/avatar/${randomId}`
        };
        
        console.log('准备上传头像，选项:', options);
        
        if (typeof module.uploadAvatar === 'function') {
          // 调用上传头像API，传递进度回调和存储配置
          module.uploadAvatar(formData, options)
            .then(response => {
              console.log('头像上传响应:', response);
              
              if (response && (response.code === 200 || response.success)) {
                // 上传成功 - 从响应中获取URL
                // 首先尝试data.avatarUrl，然后data.fileUrl，然后data本身，最后回退到预览URL
                const avatarUrl = response.data?.avatarUrl || response.data?.fileUrl || 
                                 (typeof response.data === 'string' ? response.data : null) || 
                                 previewUrl;
                                 
                this.accountSettings.avatar = avatarUrl;
                this.showSaveResult(true, '头像上传成功');
                
                // 清除相关缓存
                sessionStorage.removeItem('profileData');
                localStorage.removeItem('cachedUserInfo');
              } else {
                // 上传失败
                this.showSaveResult(false, response?.message || '头像上传失败');
              }
            })
            .catch(error => {
              console.error('头像上传失败:', error);
              
              // 如果是API不存在，使用本地预览模式
              if (error.message && error.message.includes('API')) {
                this.accountSettings.avatar = previewUrl;
                this.showSaveResult(true, '头像已更新（预览模式）');
              } else {
                this.showSaveResult(false, '头像上传失败: ' + error.message);
              }
            })
            .finally(() => {
              // 重置上传进度
              setTimeout(() => {
                this.uploadProgress = 0;
              }, 1000);
            });
        } else {
          // 如果API不存在，使用预览模式
          console.warn('uploadAvatar API不存在，使用预览模式');
          this.accountSettings.avatar = previewUrl;
          this.showSaveResult(true, '头像已更新（预览模式）');
        }
      }).catch(error => {
        console.error('导入oss模块失败:', error);
        // 使用预览模式
        this.accountSettings.avatar = previewUrl;
        this.showSaveResult(true, '头像已更新（预览模式）');
        this.uploadProgress = 0;
      });
    },
    
    // 删除头像
    removeAvatar() {
      if (confirm('确定要删除头像吗？')) {
        this.accountSettings.avatar = '';
        this.showSaveResult(true, '头像已删除');
        
        // 调用API删除头像
        import('@/api/oss').then(module => {
          if (typeof module.removeAvatar === 'function') {
            module.removeAvatar(this.accountSettings.userName)
              .then(response => {
                if (!(response && (response.code === 200 || response.success))) {
                  console.warn('API删除头像失败，但UI已更新');
                }
              })
              .catch(error => {
                console.error('删除头像API调用失败:', error);
              });
          }
        }).catch(error => {
          console.error('导入oss模块失败:', error);
        });
      }
    }
  }
}
</script>

<style scoped>
.settings-page {
  padding: 30px 0;
}

.page-title {
  font-size: 28px;
  color: #333;
  margin-bottom: 30px;
}

.settings-container {
  display: flex;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.settings-sidebar {
  width: 250px;
  background-color: #f9f9f9;
  border-right: 1px solid #eee;
}

.settings-menu {
  list-style: none;
  padding: 0;
  margin: 0;
}

.menu-item {
  padding: 15px 20px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
  transition: all 0.3s;
}

.menu-item:hover {
  background-color: #f1f8f1;
}

.menu-item.active {
  background-color: #4CAF50;
  color: white;
}

.settings-content {
  flex: 1;
  padding: 30px;
}

.section-title {
  margin-top: 0;
  margin-bottom: 0;
  color: #333;
  font-size: 24px;
}

.subsection-title {
  margin-top: 30px;
  margin-bottom: 15px;
  color: #555;
  font-size: 18px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.settings-form {
  max-width: 600px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #555;
}

.form-control {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-control:focus {
  border-color: #4CAF50;
  outline: none;
}

.form-control:disabled {
  background-color: #f9f9f9;
  cursor: not-allowed;
}

.form-textarea {
  min-height: 100px;
}

.form-note {
  margin-top: 5px;
  font-size: 14px;
  color: #888;
}

.form-actions {
  margin-top: 30px;
}

.btn {
  padding: 10px 20px;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
  font-size: 16px;
}

.btn-primary {
  background-color: #4CAF50;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: #3d8b40;
}

.btn-primary:disabled {
  background-color: #a5d6a7;
  cursor: not-allowed;
}

.radio-group {
  display: flex;
  gap: 20px;
}

.radio-label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.radio-label input {
  margin-right: 8px;
}

.switch-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.switch-label {
  flex: 1;
}

.switch-label h3 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #333;
}

.switch-label p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 34px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #4CAF50;
}

input:focus + .slider {
  box-shadow: 0 0 1px #4CAF50;
}

input:checked + .slider:before {
  transform: translateX(26px);
}

.checkbox-group {
  margin-bottom: 15px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.checkbox-label input {
  margin-right: 10px;
}

.save-result {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px 20px;
  border-radius: 4px;
  z-index: 1000;
  animation: slideIn 0.3s ease-out;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.save-result.success {
  background-color: #4CAF50;
  color: white;
}

.save-result.error {
  background-color: #f44336;
  color: white;
}

@keyframes slideIn {
  from {
    transform: translateY(-20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(76, 175, 80, 0.1);
  border-radius: 50%;
  border-top-color: #4CAF50;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-container {
  text-align: center;
  padding: 40px 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.error-container h3 {
  color: #d32f2f;
  margin-bottom: 15px;
}

@media (max-width: 768px) {
  .settings-container {
    flex-direction: column;
  }
  
  .settings-sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #eee;
  }
  
  .settings-menu {
    display: flex;
    overflow-x: auto;
  }
  
  .menu-item {
    border-bottom: none;
    padding: 15px;
    white-space: nowrap;
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.btn-refresh {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  color: #555;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-refresh:hover {
  background-color: #e8f5e9;
  border-color: #4CAF50;
  color: #4CAF50;
}

.refresh-icon {
  margin-right: 5px;
  font-style: normal;
  font-size: 16px;
  animation: spin 1s linear infinite paused;
}

.btn-refresh:active .refresh-icon {
  animation-play-state: running;
}

/* 头像上传样式 */
.avatar-upload-group {
  margin-bottom: 30px;
}

.avatar-container {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.current-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  position: relative;
  cursor: pointer;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.current-avatar:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-avatar {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36px;
  color: white;
  background: linear-gradient(45deg, #4CAF50, #8BC34A);
}

.avatar-overlay {
  position: absolute;
  inset: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.current-avatar:hover .avatar-overlay {
  opacity: 1;
}

.avatar-edit-icon {
  font-size: 24px;
  color: white;
}

.avatar-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.btn-outline {
  background-color: transparent;
  border: 1px solid #4CAF50;
  color: #4CAF50;
}

.btn-outline:hover {
  background-color: rgba(76, 175, 80, 0.1);
}

.btn-sm {
  padding: 6px 12px;
  font-size: 14px;
}

.btn-danger {
  color: #f44336;
  border-color: #f44336;
}

.btn-danger:hover {
  background-color: rgba(244, 67, 54, 0.1);
}

/* 头像上传进度条样式 */
.avatar-progress {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 20px;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
}

.progress-bar {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  background: rgba(76, 175, 80, 0.8);
  transition: width 0.3s ease;
}

.progress-text {
  position: relative;
  color: white;
  font-size: 12px;
  font-weight: bold;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}
</style> 